package dao;

import java.sql.*;

public class BaseDao implements Dao{
    //加载驱动

    //取得连接
    @Override
    public Connection conn() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (Exception e){
            e.printStackTrace();
        }
        Connection conn=null;
        try {
            conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/insuredb?useUnicode=true&characterEncoding=utf-8", "root", "Qq7788110");
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }


    //取得pstmt
    @Override
    public PreparedStatement pstmt(String sql, Object [] objs) {
        Connection conn=conn();
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            //绑定参数
            if (objs!=null){
                for (int i=0;i<objs.length;i++){
                    pstmt.setObject(i+1,objs[i]);
                }
            }
            return pstmt;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    //增删改
    @Override
    public int executeUpdate(String sql, Object [] objs) {
        Connection conn=conn();
        PreparedStatement pstmt=null;
        try {
            pstmt=conn.prepareStatement(sql);
            //绑定参数
            if (objs!=null){
                for (int i=0;i<objs.length;i++){
                    pstmt.setObject(i+1,objs[i]);
                }
            }
            return pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            cloesAll(conn,pstmt,null);
        }
        return 0;
    }


    //关闭资源
    @Override
    public void cloesAll(Connection conn, Statement stmt, ResultSet rs) {
        if (conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt !=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
